//会员卡
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.card;
	var db_id_prefix = config.dbIdPrefix.card;
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，会员卡信息不可为空");
		}
		var self = this;
		self._id = db_id_prefix + "B:" + info.bus_id + "|T:" + info.card_factory_id + "|U:" + info.user_id;

		self.bus_id = info.bus_id;
		self.card_factory_id = info.card_factory_id;
		// self.card_factory = CardFactoryCon.get(this.card_factory_id);
		self.user_id = info.user_id;

		self.uid = _con.buildCardUid(self);

		//使用情况
		self.info = {};
		self.setInfo({});

		self.state = _con.STATE.可用;

		self.create_time = +new Date;

		db.insert(db_table_name, self);
		console.log("生成了一个会员卡：", self._id);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");

	_con.STATE = {
		可用: 1,
		已过期: 2,
		无效: 3
	};

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		return _con.getInstance(result);
	};
	_con.getInstance = function(result) {
		if (result) {
			result.__proto__ = _con.prototype;
			result.card_factory = CardFactoryCon.get(result.card_factory_id);
			if (!result.card_factory) {
				result.state = _con.STATE.无效
				result.save();
			} else if (result.state === _con.STATE.可用 && result.card_factory.info.diedline <= +new Date) {
				result.state = _con.STATE.已过期
				result.save();
			}
		}
		return result;
	};
	//生成默认的描述信息
	_con.buildCardUid = function(instance) {
		var uid = _string_to_num(instance.bus_id, 4) + _string_to_num(instance.card_factory_id, 4) + _string_to_num(instance.user_id, 4);
		//4位校验位
		var check_code = _string_to_num(uid, 4);
		return uid + check_code;
	}

	function _string_to_num(str, bit) {
		var res = 0;
		for (var i = 0; i < str.length; i += 1) {
			res += str.charCodeAt(i);
		}
		if (bit) {
			res = String(res).substr(-bit)
		}
		return res;
	};
	_con.cardId_has_user = function(card_id, user_id) {
		return card_id.indexOf("|U:" + user_id) !== -1;
	};
	_con.cardId_has_bus = function(card_id, bus_id) {
		return card_id.indexOf("B:" + bus_id) !== -1;
	};

	var CardFactoryCon = require("../card_factory/_con");
}());